import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // baseURL: 'http://127.0.0.1:8080',
  baseURL: process.env.VUE_APP_BASE_API,
  // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use (

  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // console.log(response)
    const res = response.data
    const code = response.status
    const message = response.data.message
    const datCode = response.data.code

    const content = response.headers['content-disposition']
    if (typeof(content) !== 'undefined') {
      const fileName = response.headers['content-disposition'].match(/filename=(.*)/)[1]
      // const blob = new Blob([response.data], { type: 'application/octet-stream' })
      // const blob = new Blob([response.data], { type: 'application/vnd.ms-excel/msword' })

      // console.log(response)
      // const blob = new Blob([response.data],{type: 'application/vnd.ms-excel'})
      const blob = new Blob([response.data])
      // const blob = new Blob([response.data], { type: 'application//vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8'})
      const blobURL = window.URL.createObjectURL(blob)
      // 创建a标签，用于跳转至下载链接
      const tempLink = document.createElement('a')
      tempLink.style.display = 'none'
      tempLink.href = blobURL
      tempLink.setAttribute('download', decodeURI(fileName))

      document.body.appendChild(tempLink)
      tempLink.click()
      document.body.removeChild(tempLink)
      // 释放blob URL地址
      window.URL.revokeObjectURL(blobURL)
      // console.log(fileName)
    }

    if (code !== 200) {
      Message({
        message: message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(message || 'Error'))
    } else {
      // console.log(response)
      if (datCode==null) {
        return res
      }
      // console.log(message)
      if (datCode===401) {
        // to re-login
        if (message==='认证错误') {
          MessageBox.confirm('您的登录已超时请重新登录', '重新登录', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
        } else {
          Message({
            message: message || 'Error',
            type: 'error',
            duration: 5 * 1000
          })
        }
        return Promise.reject(new Error(message || 'Error'))
      }

      if (datCode===400) {
        Message({
          message: message,
          type: 'error',
          duration: 5 * 1000
        })
      }



      //
      //

      return res
    }
  },
  error => {
    console.log(error)
    console.log(response) // for debug


    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error)
  }
)

export default service
